package app

import (
	"git.huoys.com/block_chain/mall/ecode"
	"net/http"

	"github.com/gin-gonic/gin"
)

type Response struct {
	Ctx *gin.Context
}

type Pager struct {
	// 页码
	Page int64 `json:"page"`
	// 每页数量
	PageSize int64 `json:"page_size"`
	// 总行数
	TotalRows int64 `json:"total_rows"`
}

func NewResponse(ctx *gin.Context) *Response {
	return &Response{
		Ctx: ctx,
	}
}

func (r *Response) ToResponse(data interface{}) {
	if data == nil {
		data = gin.H{}
	}
	r.Ctx.JSON(http.StatusOK, data)
}

func (r *Response) ToResponseList(list interface{}, totalRows int64) {
	r.Ctx.JSON(http.StatusOK, gin.H{
		"list": list,
		"pager": Pager{
			Page:      GetPage(r.Ctx),
			PageSize:  GetPageSize(r.Ctx),
			TotalRows: totalRows,
		},
	})
}

func (r *Response) ToErrorResponse(err error) {
	var errCode = ecode.Cause(err)
	response := gin.H{"code": errCode.Code(), "msg": errCode.Message()}
	details := errCode.Details()
	if len(details) > 0 {
		response["details"] = details
	}

	r.Ctx.JSON(errCode.Code(), response)
}
